package com.guchenbo.nacos.spring.boot;

import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

public class OverridePropertyApplicationListener implements SmartApplicationListener {
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationContextInitializedEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationContextInitializedEvent) {
            ApplicationContextInitializedEvent e = (ApplicationContextInitializedEvent) event;
            ConfigurableEnvironment environment = e.getApplicationContext().getEnvironment();
            // 本地配置优先
            MutablePropertySources propertySources = environment.getPropertySources();
            if (propertySources.contains("application")) {
                PropertySource propertySource = propertySources.remove("application");
                propertySources.addFirst(propertySource);
            }

        }
    }
}
